import http.server
import socketserver
import mimetypes
import os
from pathlib import Path

# 添加Vue文件的MIME类型支持
mimetypes.add_type('text/javascript', '.js')
mimetypes.add_type('application/javascript', '.mjs')
mimetypes.add_type('text/css', '.css')
mimetypes.add_type('application/json', '.json')
mimetypes.add_type('image/svg+xml', '.svg')
mimetypes.add_type('text/html', '.html')
mimetypes.add_type('application/wasm', '.wasm')
mimetypes.add_type('application/javascript', '.vue')

class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def guess_type(self, path):
        """根据文件扩展名猜测MIME类型"""
        mimetype, encoding = mimetypes.guess_type(path)
        # 特别处理.js和.vue文件，确保它们被视为JavaScript模块
        if path.endswith('.js') or path.endswith('.mjs') or path.endswith('.vue'):
            return 'application/javascript'
        return mimetype or 'application/octet-stream'

    def end_headers(self):
        # 添加CORS头以允许跨域请求
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

def start_server(port=8080, directory='.'):
    """启动Web服务器"""
    # 切换到webui目录
    os.chdir(directory)
    
    # 创建处理器
    handler = CustomHTTPRequestHandler
    
    # 创建服务器
    with socketserver.TCPServer(("", port), handler) as httpd:
        print(f"Web服务器启动在 http://localhost:{port}")
        print(f"服务目录: {os.getcwd()}")
        print("按 Ctrl+C 停止服务器")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n服务器已停止")

if __name__ == "__main__":
    # 启动服务器，端口8080，服务webui目录
    start_server(8080, '.')